
const redisClient = require('./redisClient');
module.exports = {
    // 如果用户密码有效，则连接被许可
    authenticate: function (client, username, password, callback) {
        let authorized = false;
        if (redisClient !== null && username != null && password != null) {
            console.log(`password:${password}`);
            redisClient.get(password, (err, reply) => {
                if (!err && reply) {
                    client.user = username;
                    authorized = true;
                }
                console.log(`验证是否成功：${authorized}`);
                callback(null, authorized);
            })
        } else {
            if (username.indexOf("visitor") != -1) {
                //存储了一下用户名
                client.user = username;
                authorized = true;
            }
            console.log(authorized);
            callback(null, authorized);
        }
    },
    // 在这样的情况下，被认证为"alice"的客户端可以向 /users/alice 主题发布消息
    // the username from the topic and verifing it is the same of the authorized user（解释一下他巧妙地通过split（）对topic中的用户名判断是否与username相符）
    authorizePublish: function (client, topic, payload, callback) {
        callback(null, client.user == topic.split('/')[1]);
    },
    // 在这样的情况下，被认证为"alice"的客户端可以订阅 /users/alice 主题
    // the username from the topic and verifing it is the same of the authorized user
    authorizeSubscribe: function (client, topic, callback) {
        callback(null, topic.startsWith('system') || client.user == topic.split('/')[1]);
    }
}